package com.wanmait.demo.webcontroller.usercontroller;

import com.aliyuncs.CommonRequest;
import com.aliyuncs.CommonResponse;
import com.aliyuncs.DefaultAcsClient;
import com.aliyuncs.IAcsClient;
import com.aliyuncs.exceptions.ClientException;
import com.aliyuncs.exceptions.ServerException;
import com.aliyuncs.http.MethodType;
import com.aliyuncs.profile.DefaultProfile;
import com.wanmait.demo.pojo.Userinfo;
import com.wanmait.demo.service.UserService;
import com.wanmait.demo.util.CookieUtils;
import com.wanmait.demo.util.EncryptUtils;
import com.wanmait.demo.util.ImageCode;
import org.apache.shiro.crypto.hash.Md5Hash;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
import java.awt.image.BufferedImage;
import java.io.IOException;
import java.util.Timer;
import java.util.TimerTask;

@Controller
public class CommonController {

    @Resource
    private UserService userService;


    @RequestMapping("/registerpager")
    public String register1() {
        return "user/ysk/register";
    }

    @RequestMapping("/shouye")
    public String shouye(){
        return "user/ysk/index";
    }



    //尹山坤

    @RequestMapping("/loginpager")
    public String login1() {


        return "user/ysk/login";

    }

    //登录//尹山坤
    @RequestMapping("/loginysk")
    public String login(HttpServletRequest request, Userinfo user, String code, String rememberMe, HttpServletResponse response, String phonenum, String phonecode) {
//手机号登陆
        if (phonenum != null) {
            String phoneinputcode = (String) request.getSession().getAttribute("phonennn");
            //验证码相同就登陆
            if (phonecode.equals(phoneinputcode)) {
                //根据手机号查出用户
                //System.out.println(phonenum);
                Userinfo userinfo = userService.checkphonenum(new Md5Hash(phonenum, "", 5).toString());//JSP中验证手机号是否存在；
                //System.out.println("用户");
                //System.out.println(userinfo);
                if (userinfo != null)//应该不等于空  为防止出异常  加if判断
                {
                    request.getSession().setAttribute("loginUser", userinfo);
                   // System.out.println(rememberMe);
                    if (rememberMe != null) {  //判断是否记住我
                        System.out.println(userinfo.getUserName());
                        System.out.println(userinfo.getUserPass());
                        CookieUtils.write("username", EncryptUtils.encrypt(userinfo.getUserName(), 3), "/", 60 * 60 * 24 * 30, response);
                        CookieUtils.write("password", EncryptUtils.encrypt(userinfo.getUserPass(), 3), "/", 60 * 60 * 24 * 30, response);
                        //System.out.println("cookie  手机号成功");

                    }


                } else {
                    return "redirect:/loginphone?errMes=1";
                }
                return "user/ysk/index";


            }
            //不相同就返回登录界面
            else {
                //提示验证码错误
                return "redirect:/loginphone?errMes=2";
            }

        }


//账号密码登陆

        else {


            Md5Hash md5Hash = new Md5Hash(user.getUserPass(), "", 5);
            String password = md5Hash.toString();
            //System.out.println(password);
            Userinfo userinfo1 = new Userinfo();
            userinfo1.setUserName(user.getUserName());
            userinfo1.setUserPass(password);
            //System.out.println(userinfo1.getUserPass());
            //System.out.println(userinfo1.getUserName());
            Userinfo userinfo = userService.findUser(userinfo1);

            String rightcode = (String) request.getSession().getAttribute("code");
            if (rightcode.equalsIgnoreCase(code)) {


                if (userinfo != null) {
                    request.getSession().setAttribute("loginUser", userinfo);
                   // System.out.println(rememberMe);
                    if (rememberMe != null) {
                       // System.out.println(userinfo.getUserName());
                       // System.out.println(userinfo.getUserPass());
                        //写cookie
                        CookieUtils.write("username", EncryptUtils.encrypt(userinfo.getUserName(), 3), "/", 60*60*24*30, response);
                        CookieUtils.write("password", EncryptUtils.encrypt(userinfo.getUserPass(), 3), "/", 60*60*24*30, response);
                       // System.out.println("cookie姓名"+""+EncryptUtils.encrypt(userinfo.getUserName(),3));
                       // System.out.println("cookie密码"+""+EncryptUtils.encrypt(userinfo.getUserPass(),3));

                        //System.out.println("cookie  账号成功");

                    }

                    return "user/ysk/index";
                } else {

                    return "redirect:/loginpager?errMes=1";
                }
            } else {
                return "redirect:/loginpager?errMes=2";
            }

        }
    }

    @RequestMapping("/loginphone")
    public String loginphone(){
        return "user/ysk/phonelogin";

    }




    //画验证码//尹山坤
    @RequestMapping("/code")
    public void code(HttpServletRequest request, HttpServletResponse response) throws IOException {
        ImageCode imageCode = new ImageCode();
        BufferedImage image = imageCode.getImage();
        request.getSession().setAttribute("code", imageCode.getText());
        ImageCode.output(image, response.getOutputStream());

    }

    //验证码//尹山坤
    @RequestMapping("/checkcode")
    @ResponseBody
    public String checkcode(String code, HttpServletRequest request) {
        String rightcode = (String) request.getSession().getAttribute("code");
        if (rightcode != null && rightcode.equalsIgnoreCase(code)) {
            return "pass";
        } else {


            return "not";
        }

    }


    //退出//尹山坤
    @RequestMapping("/exit")
    public String exit(HttpServletRequest request, HttpServletResponse response) {
        HttpSession session = request.getSession();
        //让整个session失效
        //session.invalidate();
        session.removeAttribute("loginUser");
        //删除cookie 设置过期时间为0
        CookieUtils.write("username", "", "/", 0, response);
        CookieUtils.write("password", "", "/", 0, response);
        return "user/ysk/login";

    }

    //尹山坤
    @RequestMapping("/user/indexysk")
    public String index() {


        return "user/ysk/index";

    }


    //修改密码界面//尹山坤
//       @RequestMapping("/changeuserpasspager")
//    public String changeuserpass() {
//        return "user/ysk/changeuserpass";
//    }



//注册  尹山坤
    @RequestMapping("/regist")
    public String  regist(String username, String userpass,String phonenum) {
        //System.out.println("提交表单成功");
        userService.insertuser(username, new Md5Hash(userpass, "", 5).toString(), new Md5Hash(phonenum, "", 5).toString());
        return "user/ysk/login";
    }


    @ResponseBody
    @RequestMapping("/checkusername")//检查用户名是否重复 尹山坤
    public String checkusername(String username) {
        Userinfo userinfo = userService.checkusername(username);
        if (userinfo == null) {
            return "ok";
        } else {
            return "no";
        }

    }

    //手机验证码接受 尹山坤
    @RequestMapping("/phonenum")
    @ResponseBody
    public void phonenum(String phone,String code,HttpSession session) {

        DefaultProfile profile = DefaultProfile.getProfile("cn-hangzhou", "LTAI4GA2YMurRcWgspL2KWda", "WWsepdMBq5OjJgkFIwMhMDFGHGJA8S");
        IAcsClient client = new DefaultAcsClient(profile);
        session.setAttribute("phonennn",code);
        System.out.println(code);

        CommonRequest request = new CommonRequest();
        request.setSysMethod(MethodType.POST);
        request.setSysDomain("dysmsapi.aliyuncs.com");
        request.setSysVersion("2017-05-25");
        request.setSysAction("SendSms");
        request.putQueryParameter("RegionId", "cn-hangzhou");
        request.putQueryParameter("PhoneNumbers", phone);
        request.putQueryParameter("SignName", "ABC商城");
        request.putQueryParameter("TemplateCode", "SMS_205462689");
        request.putQueryParameter("TemplateParam","{code:\""+code+"\"}");
        try {
            //验证码5分钟内有效
            final Timer timer=new Timer();
            timer.schedule(new TimerTask() {
                @Override
                public void run() {
                    session.removeAttribute("phonennn");
                    System.out.println("session删除成功");
                    timer.cancel();
                }
            },5*60*1000);


            CommonResponse response = client.getCommonResponse(request);
            System.out.println(response.getData());
        } catch (ServerException e) {
            e.printStackTrace();
        } catch (ClientException e) {
            e.printStackTrace();
        }
    }
//检查手机验证码是否正确 尹山坤
    @RequestMapping("/checkphonecode")
    @ResponseBody
    public String checkphonecode(String phonenum,HttpSession session){
       String code= (String)session.getAttribute("phonennn");
      System.out.println(code);
        //System.out.println("111111111111");
     System.out.println(phonenum);
       if(phonenum.equals(code)){
           return "yes";
       }
       else {
           return "no";
       }
    }

//检查手机号是否被使用
    @ResponseBody
    @RequestMapping("/checkuserphone")
    public String checkuserphone(String phonenum){
        Userinfo userinfo=userService.checkphonenum(new Md5Hash(phonenum,"",5).toString());
        if(userinfo==null){
            return "no";
        }
        else {
            return "yes";
        }
    }


//手机号登录界面
    @RequestMapping("/phoneloginpager")
    public String phoneloginpager(){
        return "user/ysk/phonelogin";
    }


    //忘记密码界面
   @RequestMapping("/forgetpager")
   public String forgetpager(){
        return "user/ysk/forgetpassword";
   }


//忘记密码
    @RequestMapping("/forgetpassword")
    public String forgetpassword(String phonenum,String phonecode,HttpSession session,String userword){

        Userinfo userinfo=userService.checkphonenum(new Md5Hash(phonenum,"",5).toString());
        if(userinfo!=null){

        String code=(String)session.getAttribute("phonennn");
        if(code.equals(phonecode)){
            userService.updatauserpass(userinfo.getId(),new Md5Hash(userword,"",5).toString());
            //修改密码
            return "user/ysk/login";
        }
        else
        {
            return "redirect:/forgetpager?errMes=1";
            //返回修改密码界面   错误信息验证码不正确
        }
        }
        else {
            return "redirect:/forgetpager?errMes=2";   //该用户未注册
        }

    }








}





